// API工具函数
export const getAuthToken = () => {
  // 从环境变量获取token
  const envToken = import.meta.env.VITE_AUTH_TOKEN
  if (envToken) {
    return envToken
  }
  
  // 从localStorage获取token
  const localToken = localStorage.getItem('auth_token')
  if (localToken) {
    return localToken
  }
  
  // 从sessionStorage获取token
  const sessionToken = sessionStorage.getItem('auth_token')
  if (sessionToken) {
    return sessionToken
  }
  
  return null
}

// 设置认证令牌
export const setAuthToken = (token) => {
  localStorage.setItem('auth_token', token)
}

// 清除认证令牌
export const clearAuthToken = () => {
  localStorage.removeItem('auth_token')
  sessionStorage.removeItem('auth_token')
}

// 构建请求头
export const buildHeaders = (customHeaders = {}) => {
  const headers = {
    'Content-Type': 'application/json',
    'Accept': 'application/json',
    ...customHeaders
  }
  
  const token = getAuthToken()
  if (token) {
    headers['Authorization'] = `Bearer ${token}`
  }
  
  return headers
}

// API请求封装
export const apiRequest = async (url, options = {}) => {
  const defaultOptions = {
    method: 'GET',
    mode: 'cors',
    credentials: 'include',
    headers: buildHeaders(options.headers)
  }
  
  const mergedOptions = { ...defaultOptions, ...options }
  
  // 重试机制
  const maxRetries = 3
  for (let i = 0; i < maxRetries; i++) {
    try {
      const response = await fetch(url, mergedOptions)
      
      if (response.ok) {
        return response
      }
      
      // 处理认证错误
      if (response.status === 401) {
        clearAuthToken()
        throw new Error('认证失败，请重新登录')
      }
      
      throw new Error(`HTTP ${response.status}: ${response.statusText}`)
    } catch (err) {
      if (i === maxRetries - 1) {
        throw err
      }
      console.warn(`请求失败，正在重试... (${i + 1}/${maxRetries})`)
      await new Promise(resolve => setTimeout(resolve, 1000 * (i + 1)))
    }
  }
}

// 获取API基础URL
// API配置管理
export const API_CONFIG = {
  // 基础URL配置
  BASE_URL: import.meta.env.VITE_API_BASE_URL || 'http://localhost:8888',
  
  // 所有API端点配置
  ENDPOINTS: {
    // SMIS工单相关
    WORK_ORDERS_FROM_TXT: '/api/work-orders-from-txt',
    SMIS_INVENTORY: '/api/smis-inventory',
    SMIS_WORK_ORDER_MATERIALS: '/api/smis-work-order-materials',
    
    // U9生产订单相关
    U9_PRODUCTION_ORDERS: '/api/u9-production-orders',
    
    // U9库存相关
    U9_INVENTORY: '/api/u9-inventory',
    
    // 齐套分析相关
    KIT_ANALYSIS: '/api/kit-analysis',
    
    // 健康检查
    HEALTH_CHECK: '/api/health'
  }
}

// 获取API基础URL
export const getApiBaseUrl = () => {
  return API_CONFIG.BASE_URL
}

// 获取完整的API端点URL
export const getApiEndpoint = (endpointKey) => {
  const endpoint = API_CONFIG.ENDPOINTS[endpointKey]
  if (!endpoint) {
    throw new Error(`未找到端点配置: ${endpointKey}`)
  }
  
  // 在开发环境中使用相对路径，让Vite代理处理；在生产环境中使用完整URL
  return import.meta.env.DEV ? endpoint : `${API_CONFIG.BASE_URL}${endpoint}`
}

// 获取工单数据
export const getWorkOrders = async () => {
  try {
    const endpoint = getApiEndpoint('WORK_ORDERS_FROM_TXT')
    const response = await apiRequest(endpoint)
    
    if (response.ok) {
      const data = await response.json()
      return data
    } else {
      throw new Error(`获取工单数据失败: ${response.status}`)
    }
  } catch (error) {
    console.error('获取工单数据失败:', error)
    throw error
  }
}

// 获取SMIS配料岛库存数据
export const getSMISInventory = async () => {
  try {
    const endpoint = getApiEndpoint('SMIS_INVENTORY')
    const response = await apiRequest(endpoint)
    
    if (response.ok) {
      const data = await response.json()
      return data
    } else {
      throw new Error(`获取SMIS配料岛库存数据失败: ${response.status}`)
    }
  } catch (error) {
    console.error('获取SMIS配料岛库存数据失败:', error)
    throw error
  }
}

// 获取SMIS工单物料数据
export const getSMISWorkOrderMaterials = async (orderno = null) => {
  try {
    let endpoint = getApiEndpoint('SMIS_WORK_ORDER_MATERIALS')
    
    // 如果提供了orderno参数，添加查询参数
    if (orderno) {
      endpoint += `?orderno=${encodeURIComponent(orderno)}`
    }
    
    const response = await apiRequest(endpoint)
    
    if (response.ok) {
      const data = await response.json()
      return data
    } else {
      throw new Error(`获取SMIS工单物料数据失败: ${response.status}`)
    }
  } catch (error) {
    console.error('获取SMIS工单物料数据失败:', error)
    throw error
  }
}

// 获取U9生产订单数据
export const getU9ProductionOrders = async () => {
  try {
    const endpoint = getApiEndpoint('U9_PRODUCTION_ORDERS')
    const response = await apiRequest(endpoint)
    
    if (response.ok) {
      const data = await response.json()
      return data
    } else {
      throw new Error(`获取U9生产订单数据失败: ${response.status}`)
    }
  } catch (error) {
    console.error('获取U9生产订单数据失败:', error)
    throw error
  }
}

// 获取U9库存数据
export const getU9Inventory = async (items = []) => {
  try {
    // 如果物料清单为空，返回空数据而不是失败
    if (!items || items.length === 0) {
      return []
    }

    const itemsArray = Array.isArray(items) ? items : [items]
    const allInventoryData = []
    
    // 批量并行查询物料库存（限制并发数避免服务器过载）
    const batchSize = 10000 // 每批最多10000个并发请求
    const batches = []
    
    for (let i = 0; i < itemsArray.length; i += batchSize) {
      const batch = itemsArray.slice(i, i + batchSize)
      batches.push(batch)
    }
    
    // 逐批处理，每批内部并行
    for (const batch of batches) {
      const batchPromises = batch.map(async (itemCode) => {
        if (!itemCode || itemCode.trim() === '') return null
        
        // 构建POST请求的JSON请求体（按照U9接口要求的格式）
        const requestBody = {
          context: {
            CultureName: 'zh-CN',
            EntCode: '942',
            OrgCode: '1001',
            UserCode: 'DINGDING'
          },
          itemCode: itemCode.trim(), // 单个物料编码
          lotCode: '' // 空批次号
        }

        // 在开发环境中通过代理访问U9 API
        const u9ApiUrl = import.meta.env.DEV 
          ? '/api/u9-inventory' 
          : 'http://172.16.8.223/U9/RestServices/UFIDA.U9.Cust.YHHT.DomainMainSV.DataQueryReport.IQNanTongWhQoh.svc/do'
        
        try {
          const response = await apiRequest(u9ApiUrl, {
            method: 'POST',
            headers: {
              'Content-Type': 'application/json',
              'Accept': 'application/json'
            },
            body: JSON.stringify(requestBody)
          })
          
          if (response.ok) {
            const data = await response.json()
            
            if (data && Array.isArray(data)) {
              // 给每条记录添加物料编码标识
              return data.map(item => ({
                ...item,
                ItemCode: item.ItemCode || itemCode,
                itemCode: item.itemCode || itemCode
              }))
            } else if (data) {
              // 单条记录
              return {
                ...data,
                ItemCode: data.ItemCode || itemCode,
                itemCode: data.itemCode || itemCode
              }
            }
          }
          return null
        } catch (itemError) {
          // 忽略单个物料查询失败，继续查询其他物料
          return null
        }
      })
      
      // 等待当前批次完成
      const batchResults = await Promise.allSettled(batchPromises)
      
      // 收集成功的结果
      batchResults.forEach(result => {
        if (result.status === 'fulfilled' && result.value) {
          if (Array.isArray(result.value)) {
            allInventoryData.push(...result.value)
          } else {
            allInventoryData.push(result.value)
          }
        }
      })
      
      // 批次间添加短暂延迟，避免服务器过载
      if (batches.indexOf(batch) < batches.length - 1) {
        await new Promise(resolve => setTimeout(resolve, 200))
      }
    }
    
    return allInventoryData
    
  } catch (error) {
    // 返回空数组而不是抛出错误，让分析可以继续进行
    return []
  }
}

// 齐套分析相关接口
export const performKitAnalysis = async (workOrderId, materials = []) => {
  try {
    // 并行获取SMIS配料岛库存和U9库存数据
    const [smisInventory, u9Inventory] = await Promise.all([
      getSMISInventory(),
      getU9Inventory(materials)
    ])

    return {
      workOrderId,
      smisInventory,
      u9Inventory,
      timestamp: new Date().toISOString()
    }
  } catch (error) {
    console.error('齐套分析失败:', error)
    throw error
  }
}
